package cn.cloud.all.security.web;

import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

public class PortMapperImpl implements PortMapper {

    private final Map<Integer, Integer> httpsPortMappings;

    public PortMapperImpl() {
        this.httpsPortMappings = new HashMap<>();
        this.httpsPortMappings.put(80, 443);
        this.httpsPortMappings.put(8080, 8443);
    }

    public Map<Integer, Integer> getTranslatedPortMappings() {
        return this.httpsPortMappings;
    }

    public Integer lookupHttpPort(Integer httpsPort) {
        for (Integer httpPort : this.httpsPortMappings.keySet()) {
            if (this.httpsPortMappings.get(httpPort).equals(httpsPort)) {
                return httpPort;
            }
        }
        return null;
    }

    public Integer lookupHttpsPort(Integer httpPort) {
        return this.httpsPortMappings.get(httpPort);
    }

    public void setPortMappings(Map<String, String> newMappings) {
        Assert.notNull(newMappings, "A valid list of HTTPS port mappings must be provided");
        this.httpsPortMappings.clear();

        for (Map.Entry<String, String> entry : newMappings.entrySet()) {
            int httpPort = Integer.parseInt(entry.getKey());
            int httpsPort = Integer.parseInt(entry.getValue());
            if ((httpPort < 1) || (httpPort > 65535) || (httpsPort < 1) || (httpsPort > 65535)) {
                throw new IllegalArgumentException("one or both ports out of legal range: " + httpPort + ", " + httpsPort);
            }
            this.httpsPortMappings.put(httpPort, httpsPort);
        }

        if (this.httpsPortMappings.size() < 1) {
            throw new IllegalArgumentException("must map at least one port");
        }
    }
}
